#!/bin/bash -ex
# Copyright (c) Contributors to the Apptainer project, established as
#   Apptainer a Series of LF Projects LLC.
#   For website terms of use, trademark policy, privacy policy and other
#   project policies see https://lfprojects.org/policies

# this script runs as root under docker --privileged

# install dependencies
apt-get update
export DEBIAN_FRONTEND=noninteractive
apt-get install -y \
    build-essential \
    libseccomp-dev \
    pkg-config \
    uidmap \
    squashfs-tools \
    fakeroot \
    cryptsetup \
    tzdata \
    curl wget git
apt-get install -y \
    devscripts \
    debhelper \
    dh-autoreconf \
    help2man \
    libarchive-dev \
    libssl-dev \
    python2 \
    uuid-dev \
    golang-go
# for squashfuse_ll build
apt-get install -y autoconf automake libtool pkg-config libfuse3-dev zlib1g-dev

# move source code down a level because debuild writes into parent dir
shopt -s extglob
mkdir src
mv .??* !(src) src

# switch to an unprivileged user with sudo privileges
apt-get install -y sudo
useradd -u 1000 --create-home -s /bin/bash testuser
echo "Defaults:testuser env_keep=DOCKER_HOST" >>/etc/sudoers
echo "testuser ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
mkdir -p /local
chown -R testuser . /local

cd src

# Be careful not to use unescaped single quotes in these commands
su testuser -c '
  set -x
  set -e
  cp -r dist/debian .
  GOSRC="go$(scripts/get-min-go-version).src.tar.gz"
  if [ -n "$GOSRC" ]; then
    curl -f -L -sS -o debian/$GOSRC https://golang.org/dl/$GOSRC
    if [ -n "'$GO_ARCH'" ]; then
      # Download and install binary too to avoid debuild having to compile the
      #  go toolchain from source
      GOBIN="$(echo "$GOSRC"|sed "s/\.src./.'$GO_ARCH'./")"
      curl -f -L -sS https://golang.org/dl/$GOBIN | tar -xzf - -C /local
      PATH=/local/go/bin:$PATH
    fi
  fi
  go version
  ./scripts/download-dependencies debian
  export DEB_FULLNAME="'"${DEB_FULLNAME:-CI Test}"'"
  export DEBEMAIL="'${DEBEMAIL:-citest@example.com}'"
  debuild --prepend-path $PATH --build=binary --no-sign --lintian-opts --display-info --show-overrides
  sudo dpkg -i ../apptainer*.deb

  apptainer exec oras://ghcr.io/apptainer/alpine:3.15.0 /bin/true
'
